import 'package:demo_app_video/commons/commons.dart';
import 'package:demo_app_video/commons/http/http.dart';
import 'package:demo_app_video/commons/router/routes.dart';
import 'package:demo_app_video/widgets/items_data.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:keframe/keframe.dart';
import 'package:flutter_adcontent/flutter_adcontent.dart';

class SearchDetailsPage extends StatefulWidget {
  const SearchDetailsPage({Key? key}) : super(key: key);

  @override
  State<SearchDetailsPage> createState() => _SearchDetailsPageState();
}

class _SearchDetailsPageState extends State<SearchDetailsPage> {
  int page = 1;
  List videos = [];
  int pageNum = 1; // 当前页数
  int totalPages = 1;
  bool isLoading = false;
  TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  to_search() {
    Commons().closeBoard(context);
    onRefresh();
  }

  get_videos({isRefresh = false}) async {
    if (isLoading) {
      return;
    }
    setState(() {
      isLoading = true;
    });
    var resultData = await HttpUtil.getInstance().get('shortplay/search',
        data: {'name': _controller.text, 'page': pageNum});

    if (isRefresh) {
      videos = resultData['data']['data'];
    } else {
      videos.addAll(resultData['data']['data']);
    }
    totalPages = resultData['data']['last_page'];
    setState(() {
      isLoading = false;
    });
  }

  Future<void> onLoad() async {
    if (pageNum >= totalPages) return;
    setState(() {
      pageNum++;
    });
    await get_videos(isRefresh: false);
  }

  Future<void> onRefresh() async {
    videos.clear();
    setState(() {
      pageNum = 1;
    });
    await get_videos(isRefresh: true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xffFFFFFF),
      body: Stack(
        children: [
          Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
                image: DecorationImage(
                    image: AssetImage('images/search_bg.png'),
                    fit: BoxFit.fill)),
          ),
          Container(
            padding: EdgeInsets.only(
                top: MediaQuery.of(context).padding.top + 104.h),
            child: SizeCacheWidget(
                child: EasyRefresh(
              child: ListView.builder(
                addAutomaticKeepAlives: false,
                addRepaintBoundaries: false,
                itemBuilder: (BuildContext context, int index) {
                  var item = videos[index];
                  return InkResponse(
                    radius: 0,
                    highlightColor: Colors.transparent,
                    onTap: () async {
                      var resultData = await FlutterAdcontent.requestDrama(
                          [int.parse(item['third_movie_id'].toString())]);
                      Routes().push(context, Routes.dramaDetails,
                          {'drama': resultData.first});
                    },
                    child: ItemsDataWidgets(
                        img_url: item['thumb_image'].toString(),
                        title: item['display_name'].toString(),
                        sub_title: item['intro'].toString(),
                        subscribe: item['follow_num'].toString(),
                        all_videos: item['total_count'].toString()),
                  );
                },
                padding: EdgeInsets.only(left: 16.w),
                itemCount: videos.length,
              ),
              onLoad: onLoad,
              onRefresh: onRefresh,
              header: ClassicHeader(
                  processedText: "刷新完成",
                  processingText: "正在刷新",
                  readyText: '准备刷新',
                  armedText: "松手刷新",
                  dragText: "下拉刷新",
                  showMessage: false),
              footer: ClassicFooter(
                  processedText: "加载完成",
                  processingText: "正在加载",
                  readyText: '准备加载',
                  armedText: "松手加载",
                  dragText: "上拉加载",
                  showMessage: false),
            )),
          ),
          Container(
            height: MediaQuery.of(context).padding.top + 104.h,
            padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
            decoration: BoxDecoration(
                gradient: LinearGradient(colors: [
              Color(0xffFFF4E6),
              Color(0xffFCFBF8),
            ], begin: Alignment.centerRight, end: Alignment.centerLeft)),
            child: Column(
              children: [
                Container(
                  width: 360.w,
                  height: 44.h,
                  margin: EdgeInsets.only(left: 10.w, right: 10.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      InkWell(
                        onTap: () {
                          Routes().popNowPage(context);
                        },
                        child: Image.asset(
                          'images/back_arrow.png',
                          width: 16.w,
                          height: 16.h,
                        ),
                      ),
                      Text(
                        '搜索',
                        style: TextStyle(
                            color: Color(0xff333333),
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w500),
                      ),
                      Container(
                        width: 16.w,
                      )
                    ],
                  ),
                ),
                Container(
                  width: 328.w,
                  height: 40.h,
                  margin: EdgeInsets.only(top: 10.h),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: Color(0xffFFFFFF),
                      borderRadius: BorderRadius.circular(24.sp)),
                  padding: EdgeInsets.only(left: 12.w, right: 12.w),
                  child: Row(
                    children: [
                      SizedBox(
                        width: 200.w,
                        height: 40.h,
                        child: TextField(
                          onSubmitted: (value) => to_search(),
                          controller: _controller,
                          decoration: InputDecoration(
                              contentPadding: EdgeInsets.all(0),
                              border: OutlineInputBorder(
                                  borderSide: BorderSide.none),
                              hintText: '输入短剧名进行搜索',
                              hintStyle: TextStyle(
                                  color: Color(0xffBFBFBF), fontSize: 15.sp)),
                          scrollPadding: EdgeInsets.all(0),
                        ),
                      ),
                      Expanded(child: Container()),
                      GestureDetector(
                        onTap: () => to_search(),
                        child: Image.asset(
                          'images/search_icon.png',
                          width: 20.w,
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }
}
